<template>
  <CreateTask
    :visible="modelValue"
    :current-user-id="currentUserId"
    :default-project-id="projectId"
    :default-requirement-id="defaultRequirementId"
    :default-version-ids="defaultVersionIds"
    :default-parent-id="defaultParentId"
    :status-options="statusOptions"
    :priority-options="priorityOptions"
    :type-options="typeOptions"
    :project-options="projectOptions"
    :users="users"
    :common-tag-options="commonTagOptions"
    @update:visible="handleVisibleChange"
    @created="handleTaskCreated"
  />
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { useTaskStates } from '@/composables/useTaskStates'
import { getUsers } from '@/api/user'
import { getProjectList } from '@/api/project'
import CreateTask from '@/views/tasks/components/CreateTask.vue'
import { TASK_TYPES } from '@/types/task'
import type { TaskStatus, TaskPriority, TaskType } from '@/types/task'

interface Props {
  modelValue: boolean
  projectId?: string
  defaultRequirementId?: string
  defaultVersionIds?: string[]
  defaultParentId?: string
}

const props = withDefaults(defineProps<Props>(), {
  projectId: '',
  defaultRequirementId: '',
  defaultVersionIds: () => [],
  defaultParentId: ''
})

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

const userStore = useUserStore()
const { loadStates, taskStates } = useTaskStates()

// 当前用户ID
const currentUserId = computed(() => userStore.userInfo?.id || '')

// 状态选项
const statusOptions = computed(() => {
  return taskStates.value.map((state: any) => ({
    value: state.code as TaskStatus,
    label: state.name
  }))
})

// 优先级选项
const priorityOptions = computed(() => [
  { value: 'lowest' as TaskPriority, label: '最低' },
  { value: 'low' as TaskPriority, label: '低' },
  { value: 'medium' as TaskPriority, label: '中' },
  { value: 'high' as TaskPriority, label: '高' },
  { value: 'urgent' as TaskPriority, label: '紧急' },
  { value: 'critical' as TaskPriority, label: '严重' },
  { value: 'blocker' as TaskPriority, label: '阻塞' }
])

// 任务类型选项
const typeOptions = computed(() => {
  return TASK_TYPES.map(type => ({
    value: type.value as TaskType,
    label: type.label
  }))
})

// 项目选项
const projectOptions = ref<{ value: string; label: string }[]>([])

// 用户列表
const users = ref<{ id: string; name: string }[]>([])

// 常用标签选项
const commonTagOptions = ref<string[]>([])

// 加载数据
const loadingData = ref(false)
const loadData = async () => {
  // 防止重复调用
  if (loadingData.value) {
    return
  }
  
  try {
    loadingData.value = true
    // 加载任务状态
    await loadStates()

    // 加载用户列表
    const usersResponse = await getUsers({ page: 1, size: 200 })
    const usersData = (usersResponse as any)?.data?.items || (usersResponse as any)?.items || []
    if (usersData.length > 0) {
      users.value = usersData.map((user: any) => ({
        id: user.id,
        name: user.name
      }))
    }

    // 加载项目列表
    const projectsResponse = await getProjectList({ page: 1, size: 200 })
    const projectsData = (projectsResponse as any)?.data?.items || (projectsResponse as any)?.items || []
    if (projectsData.length > 0) {
      projectOptions.value = projectsData.map((project: any) => ({
        value: project.id,
        label: project.name
      }))
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loadingData.value = false
  }
}

// 处理可见性变化
const handleVisibleChange = (value: boolean) => {
  emit('update:modelValue', value)
}

// 处理任务创建成功
const handleTaskCreated = () => {
  emit('success')
}

// 监听对话框打开，加载数据
watch(() => props.modelValue, (visible) => {
  if (visible && !loadingData.value) {
    loadData()
  }
})

// 组件挂载时加载数据
onMounted(() => {
  if (!loadingData.value) {
    loadData()
  }
})
</script>

